package m.jclecai.com.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.widget.Button;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.LuckyWalkBean;

import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.dialog.MyFailedDialog;
import m.jclecai.com.dialog.MyGiftDialog;
import m.jclecai.com.dialog.MyRuleDialog;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.utils.MyLog;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.responseBody.BaseBody;
import m.jclecai.com.utils.http.responseBody.LuckyWalkBody;

import m.jclecai.com.view.LuckyContainerView;
import m.jclecai.com.view.Luckywalk;

/**
 * Created by ZD on 2017/7/4.
 */

public class LuckyWalkActivity extends BaseActivity {

    @BindView(R.id.lwView)
    Luckywalk lwView;
    @BindView(R.id.btGift)
    Button btGift;
    @BindView(R.id.btStart)
    Button btStart;
    @BindView(R.id.btRule)
    Button btRule;
    @BindView(R.id.lvContainer)
    LuckyContainerView lvContainer;
    UserBean userBean;
    int page = 1;

    @Override
    protected int getContentView() {
        return R.layout.activity_lucky_walk;
    }

    @Override
    protected void initView() {
        super.initView();
        leftOptionText("");
        setTitle("大转盘");
    }

    @Override
    protected void initData() {
        super.initData();
        getGift();
        getUserGift();
        userBean = PreferenceUtil.readUser(this);
        if(userBean != null) {
            lvContainer.addMyGoldView(String.valueOf(userBean.getUser_goldcoin()));
        }
    }

    //奖品列表
    void getGift() {
        showDialog();
        HttpManager.getAsyn(Constant_Url.LUCKY_LIST, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                MyLog.i(request.toString());
                dissDialog();
                DisPlay(getString(R.string.faile_network));
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                LuckyWalkBody luckyWalkBody = FastOk.get(response, LuckyWalkBody.class);
                if (luckyWalkBody != null) {
                    if (luckyWalkBody.getStatus() == 0) {
                        List<LuckyWalkBean> records = luckyWalkBody.getRecords();
                        lwView.setDatas(records);
                    } else {
                        DisPlay(luckyWalkBody.getMessage());
                    }
                } else {
                    DisPlay(getString(R.string.faile_network));
                }

            }
        });
    }

    //获奖用户
    void getUserGift() {
        HttpManager.getAsyn(Constant_Url.USER_LUCKY_LIST, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {

                DisPlay("网络异常！");
                e.printStackTrace();
            }

            @Override
            public void onResponse(String response) {
                try {
                    if (!TextUtils.isEmpty(response)) {
                        JSONObject parse = FastOk.get(response, JSONObject.class);
                        if (parse != null && "0".equals(parse.getString("status"))) {
                            JSONArray records = parse.getJSONArray("records");
                            List<String> info = new ArrayList<>();
                            for (int i = 0; i < records.size(); i++) {
                                info.add(records.getJSONObject(i).getString("title"));
                            }
                            lvContainer.addMarqueeView(info);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    DisPlay("网络异常！");
                }
            }
        });
    }

    //获取随机的奖品
    void getRadom(final Callback callback) {
        showDialog();
        HttpManager.getAsyn(Constant_Url.LUCKY_RANDOM, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay(getString(R.string.faile_network));
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {
                    JSONArray parse = FastOk.get(response, JSONArray.class);
                    if (parse != null) {
                        if (parse.size() > 0)
                            callback.callback(parse);
                        else
                            DisPlay("进入抽奖失败");
                    } else {
                        DisPlay(getString(R.string.faile_network));
                    }
                }
            }
        });
    }

    //上传中奖结果
    void luckyDo(final Callback callback, String id) {
        showDialog();
        Map<String, String> map = new HashMap<>();
        map.put("user", PreferenceUtil.getUserName(this));
        map.put("password", PreferenceUtil.getPassword(this));
        map.put("id", id);
        HttpManager.postAsyn(Constant_Url.LUCKY_DO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay(getString(R.string.faile_network));
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {
                    BaseBody parse = FastOk.get(response, BaseBody.class);
                    if (parse != null) {
                        DisPlay(parse.getMessage());
                        if (parse.getStatus() == 0)
                            callback.callback(parse);
                    } else {
                        DisPlay(getString(R.string.faile_network));
                    }
                }
            }
        }, map);
    }

    @OnClick(R.id.btStart)
    void start() {
        btStart.setBackgroundResource(R.mipmap.go_press);
        btStart.setEnabled(false);
//        //检查金币
//        if (userBean == null || (userBean != null && userBean.getUser_goldcoin() < 50)) {
//            MyFailedDialog dialog = new MyFailedDialog(this);
//            dialog.setCallback(new Callback() {
//                @Override
//                public void callback() {
//                    super.callback();
//                    startActivity(new Intent(LuckyWalkActivity.this, TaskActivity.class));
//                    btStart.setEnabled(true);
//                    btStart.setBackgroundResource(R.mipmap.go_normal);
//                }
//            });
//            dialog.show();
//            return;
//        }
        getRadom(new Callback() {
            @Override
            public void callback(final JSONArray o) {
                super.callback(o);
                //接口拉取成功开始转圈
                lwView.start(o, new Callback() {
                    @Override
                    public void callbackSuccess() {
                        super.callbackSuccess();
                        int giftPosition = lwView.getGiftPosition();
                        String schemeId = o.getJSONObject(giftPosition).getString("schemeId");
                        //上传结果
                        luckyDo(new Callback() {
                            @Override
                            public void callbackSuccess() {
                                super.callbackSuccess();
                                //重新拉取信息
                                userBean.setUser_goldcoin(userBean.getUser_goldcoin() - 50);
                                PreferenceUtil.writeUser(LuckyWalkActivity.this, userBean);
                                lvContainer.addMyGoldView(String.valueOf(userBean.getUser_goldcoin()));
                            }
                        }, schemeId);
                        //转圈完成允许再次点击
                        btStart.setEnabled(true);
                        btStart.setBackgroundResource(R.mipmap.go_normal);
                    }
                });
            }
        });
    }

    //拉去中奖列表
    void myLuckyList(final MyGiftDialog dialog,final Callback callback) {
        showDialog();
        Map<String, String> map = new HashMap<>();
        map.put("user", PreferenceUtil.getUserName(this));
        map.put("password", PreferenceUtil.getPassword(this));
        map.put("page", String.valueOf(page));
        HttpManager.postAsyn(Constant_Url.MY_LUCKY_LIST, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                MyLog.i(request.toString());
                dissDialog();
                DisPlay(getString(R.string.faile_network));
                if(callback != null)
                    callback.callbackField();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                LuckyWalkBody luckyWalkBody = FastOk.get(response, LuckyWalkBody.class);
                if (luckyWalkBody != null) {
                    if (luckyWalkBody.getStatus() == 0) {
//                        records.clear();
//                        records.addAll(luckyWalkBody.getRecords());
                        if(luckyWalkBody.getRecords() != null
                                && luckyWalkBody.getRecords().size() > 0){
                            dialog.setBody(page,luckyWalkBody);
                        }else {
                            if(callback != null)
                                callback.callbackField();
                        }
                    } else {
                        DisPlay(luckyWalkBody.getMessage());
                        if(callback != null)
                            callback.callbackField();
                    }
                } else {
                    DisPlay(getString(R.string.faile_network));
                    if(callback != null)
                        callback.callbackField();
                }

            }
        }, map);
    }

    @OnClick(R.id.btGift)
    void gift() {
        final MyGiftDialog dialog = new MyGiftDialog(this);
        dialog.setCallback(new Callback(){
            @Override
            public void callback(final int v) {
                super.callback(v);
                page += v;
                myLuckyList(dialog,new Callback(){
                    @Override
                    public void callbackField() {
                        super.callbackField();
                        page -= v;
                    }
                });
            }
        });
        dialog.show();
        myLuckyList(dialog,null);
    }

    @OnClick(R.id.btRule)
    void rule() {
        MyRuleDialog dialog = new MyRuleDialog(this);
        dialog.show();
    }
}
